const fs = require("fs");
const { promisify } = require("util");
const { MongoClient } = require("mongodb");
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);

exports.getDb = async () => {
  let data = await readFile("./db.json", "utf8");
  return JSON.parse(data);
};

exports.serveDb = async (data) => {
  let stringData = JSON.stringify(data);
  return await writeFile("./db.json", stringData);
};

/**
 * 以下为mongodb的操作
 */
let mongodb = null;
function connnetDb() {
  const url = "mongodb://localhost:27017";
  const dbName = "test";
  return new MongoClient(url).connect().then((client) => {
    return client.db(dbName);
  });
}

exports.closeDb = async () => {
  if (mongodb) {
    await mongodb.close();
    mongodb = null;
  }
};

async function getcollection(collectionName) {
  if (!mongodb) {
    mongodb = await connnetDb();
  }
  return mongodb.collection(collectionName);
}

exports.getUsers = async () => {
  const collection = await getcollection("users");
  return await collection.find().toArray();
};

exports.addUser = async (user) => {
  const collection = await getcollection("users");
  return await collection.insertOne(user);
};

exports.updateUser = async (id, user) => {
  const collection = await getcollection("users");
  return await collection.updateOne({ _id: id }, { $set: user });
};

exports.getuser = async (id) => {
  const collection = await getcollection("users");
  return await collection.findOne({ _id: id });
};
